package cn.thornbird.orgsync.util;

import cn.thornbird.orgsync.model.Column;
import cn.thornbird.orgsync.model.Result;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.util.*;

public class WebUtil {

    public static final String API_PREFIX = "api";

    public static final String EXPORT = "export";

    public static final Set<String> ALLOWED_API_REQUESTS = new HashSet<>(Arrays.asList(new String[] {
            "/api/ping", "/api/getCaptcha", "/api/checkCaptcha",
            "/api/sendVerificationCode", "/api/checkVerificationCode",
            "/api/user/signUp", "/api/user/resetPassword"
    }));

    public static boolean isAllowedApiRequest(String uri) {
        return isApiRequest(uri) && (ALLOWED_API_REQUESTS.contains(uri) || uriStartsWith(uri, ALLOWED_API_REQUESTS));
    }

    public static boolean isApiRequest(String uri) {
        String path = URI.create(uri).getPath();
        String[] parts = path.split("/");
        return (parts.length > 1 && parts[1].equalsIgnoreCase(API_PREFIX));
    }

    public static boolean isApiExportRequest(String uri) {
        if (!isApiRequest(uri)) {
            return false;
        }
        String path = URI.create(uri).getPath();
        String[] parts = path.split("/");
        return (parts.length > 2 && parts[2].equalsIgnoreCase(EXPORT));
    }

    public static void writeExcelErrorMessageToResponse(HttpServletResponse response, String errorMessage)
            throws IOException {
        SXSSFWorkbook workbook = ExcelUtil.createWorkbook();
        List<Column> columns = new ArrayList<>();
        columns.add(new Column("result", "result"));
        Map<String, Object> record = new HashMap<>();
        record.put("result", errorMessage);
        List<Map<String, Object>> records = new ArrayList<>();
        records.add(record);
        ExcelUtil.createSheet(workbook, "result", columns, records);
        ExcelUtil.export(response, workbook, "result");
    }

    public static void writeHttpStatusToResponse(HttpServletResponse response, HttpStatus httpStatus)
            throws IOException {
        Result<?> result = Result.error(httpStatus.value(), httpStatus.getReasonPhrase());
        response.setStatus(httpStatus.value());
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.getOutputStream().print(JsonUtil.toJsonString(result));
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    private static boolean uriStartsWith(String uri, Set<String> uris) {
        boolean result = false;
        for (String value : uris) {
            if (uri.startsWith(value)) {
                result = true;
                break;
            }
        }
        return result;
    }

}
